package sql

import (
	"database/sql/driver"
	"encoding/base64"
	"fmt"
)

type Bytes []byte

// MarshalJSON on Bytes format Time field with %Y-%m-%d %H:%M:%S
func (t Bytes) MarshalJSON() ([]byte, error) {
	if t == nil {
		return []byte("null"), nil
	} else {
		formatted := fmt.Sprintf("\"%s\"", base64.StdEncoding.EncodeToString(t))
		return []byte(formatted), nil
	}
}

// Value insert text into mysql need this function.
func (t Bytes) Value() (driver.Value, error) {
	if t == nil {
		return nil, nil
	}
	return base64.StdEncoding.EncodeToString(t), nil
}

// Scan valueof Bytes []byte
func (t *Bytes) Scan(v interface{}) error {
	switch v.(type) {
	case []byte:
		value, ok := v.([]byte)
		if ok {
			data, err := base64.StdEncoding.DecodeString(string(value))
			if err == nil {
				*t = Bytes(data)
			}
			return err
		}
	case string:
		value, ok := v.(string)
		if ok {
			data, err := base64.StdEncoding.DecodeString(value)
			if err == nil {
				*t = Bytes(data)
			}
			return err
		}
	}
	return fmt.Errorf("can not convert %v to Bytes", v)
}
